import { defineResponseResolver } from '~~/mocks/define';

import db from '~~/DB';
import { v4 as uuidv4 } from 'uuid';
// import { testToken } from '~~/mocks/middleware/token';
// import { getUser } from '~~/mocks/utils/user';
import { Status } from '~~/DB/types/status.d';
import { TokenType } from '~~/DB/types/token.d';

export default defineResponseResolver(async (req, res, ctx) => {
  // consola.info(
  //   '🚀 ~ file: userInfo.get.ts:7 ~ defineResponseResolver ~ req, res, ctx:',
  //   [req, res, ctx],
  // );

  // await testToken(req, res, ctx);

  const body = await req.json();

  if (!body.refreshToken) {
    return res(ctx.status(401), ctx.json({ message: '请提供refreshToken' }));
  }
  const tokenInfo = await db.tokens.get({ token: body.refreshToken });
  // console.log(
  //   '🚀 ~ file: refreshToken.post.ts:27 ~ defineResponseResolver ~ tokenInfo:',
  //   tokenInfo,
  // );

  if (
    !tokenInfo ||
    tokenInfo.status === Status.disable ||
    Date.now() > tokenInfo.expirationTime.getTime()
  ) {
    return res(
      ctx.status(401),
      ctx.json({ message: 'token已失效, 请重新登录' }),
    );
  }

  // console.log(tokenInfo);

  const token = uuidv4();

  // 查找旧的token进行覆盖
  const oldToken = await db.tokens.get({
    uid: tokenInfo.uid,
    type: TokenType.token,
  });

  await db.tokens.put({
    id: oldToken?.id,
    token,
    uid: tokenInfo.uid,
    status: Status.enable,
    type: TokenType.token,
    createTime: new Date(),
    expirationTime: new Date(Date.now() + 1000 * 60 * 10),
  });

  return res(ctx.json({ token }));
  // return res(ctx.json({}));
});
